<template>
  <div class="app-container">
    <div class="head-container">
      <el-form :model="query"
               inline>
        <el-form-item label="号码：">
          <el-input v-model="query.tell"
                    placeholder="请输入号码"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="是否可办理：">
          <el-select v-model="query.is_valid"
                     placeholder="请选择"
                     clearable>
            <el-option label="是"
                       value="是"></el-option>
            <el-option label="否"
                       value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反馈情况：">
          <el-select v-model="query.res"
                     placeholder="请选择"
                     clearable>
            <el-option label="已办理"
                       value="已办理"></el-option>
            <el-option label="办理失败"
                       value="办理失败"></el-option>
            <el-option label="未反馈"
                       value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker v-model="query.create_time"
                          type="daterange"
                          align="right"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="success"
                     size="small"
                     icon="el-icon-search"
                     @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-button @click="handleDialog('create',null)"
                 type="primary"
                 size="small"
                 icon="el-icon-plus">新增</el-button>
      <el-button size="small"
                 type="success"
                 @click="handleImport"
                 v-permission="['admin']"
                 icon="el-icon-upload2">批量导入</el-button>
      <el-button size="small"
                 type="warning"
                 @click="exportNumber"
                 :loading="exportLoading"
                 icon="el-icon-download">导出</el-button>
      <el-button type="warning"
                 size="small"
                 icon="el-icon-goods"
                 @click="queryHandleDialog">查询办理情况</el-button>
    </div>
    <el-table :data="taskData"
              border
              height="700"
              v-loading="loading"
              style="width:100%">
      <el-table-column align="center"
                       label="号码"
                       prop="tell" />

      <el-table-column align="center"
                       label="是否可以办理"
                       prop="is_valid" />
      <el-table-column align="center"
                       label="渠道"
                       prop="chnl" />
      <el-table-column align="center"
                       label="创建时间">
        <template slot-scope="scope">
          {{parseTime(scope.row.create_time)}}
        </template>
      </el-table-column>
      <el-table-column align="center"
                       label="办理人"
                       prop="handler_man">
      </el-table-column>
      <el-table-column align="center"
                       label="创建人工号"
                       prop="creator" />
      <el-table-column align="center"
                       label="创建人姓名"
                       prop="nick_name" />
      <el-table-column align="center"
                       label="反馈情况">
        <template slot-scope="scope">
          <span>
            <el-tag v-if="scope.row.res === '' || scope.row.res === null"
                    type="warning">未反馈</el-tag>
            <el-tag v-if="scope.row.res !== ''"
                    type="success">{{scope.row.res}}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       prop="is_freeze"
                       label="是否冻结">

      </el-table-column>
      <el-table-column align="center"
                       prop="is_convert"
                       label="是否兑换">
      </el-table-column>
      <el-table-column align="center"
                       width="250"
                       label="操作">
        <template slot-scope="scope">
          <div>
            <el-button type="warning"
                       icon="el-icon-edit"
                       size="small"
                       @click="handleDialog('update',scope.row)">号码反馈</el-button>
            <el-button v-permission="['admin']"
                       type="primary"
                       size="small"
                       @click="handleResDialog(scope.row.id)">结果反馈</el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="small"
                       :loading="delLoading"
                       v-permission="['admin']"
                       @click="handleDelete(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page.sync="page"
                   :page-size="size"
                   layout="total, prev, pager, next"
                   :total="total">
    </el-pagination>
    <el-dialog title="结果反馈"
               :visible.sync="resDialog"
               width="30%">
      <el-form :model="resForm"
               label-width="100px">
        <el-form-item label="结果反馈：">
          <el-select v-model="resForm.res"
                     placeholder="请输入反馈信息"
                     clearable>
            <el-option label="已办理"
                       value="已办理"></el-option>
            <el-option label="办理失败"
                       value="办理失败"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handlerRes"
                     type="success"
                     size="small">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="号码编辑"
               :visible.sync="editDialog"
               width="40%">
      <el-form :model="form"
               ref="form"
               :rules="rules"
               label-width="120px">
        <el-form-item label="号码："
                      prop="tell">
          <el-input v-model="form.tell"
                    :disabled="type === 'update'"
                    placeholder="请输入号码"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="办理人："
                      prop="handler_man">
          <el-input v-model="form.handler_man"
                    :disabled="type === 'update'"
                    placeholder="请输入办理人"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="渠道："
                      v-if="type === 'update'">
          <el-input v-model="form.chnl"
                    placeholder="请输入渠道"
                    :disabled="type === 'update'"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="是否冻结："
                      v-if="type === 'update'">
          <el-select v-model="form.is_freeze"
                     placeholder="请选择"
                     clearable>
            <el-option label="是"
                       value="是"></el-option>
            <el-option label="否"
                       value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否兑换："
                      v-if="type === 'update'">
          <el-select v-model="form.is_convert"
                     placeholder="请选择"
                     clearable>
            <el-option label="是"
                       value="是"></el-option>
            <el-option label="否"
                       value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success"
                     @click="submit"
                     :loading="uploadLoading"
                     size="small">提交</el-button>
          <el-button type="info"
                     @click="editDialog = false"
                     size="small">返回</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="号码导入"
               :visible.sync="importDialog"
               width="50%">
      <div>
        <el-row>

          <el-col :span="4">
            <p>号码导入:</p>
          </el-col>
          <el-col :span="4">
            <el-button size="small"
                       @click="downloadFileByPath(path,'xlsx')"
                       type="info">模板下载</el-button>
          </el-col>
          <el-col :span="12">
            <el-upload class="upload-demo"
                       ref="upload"
                       action="#"
                       accept=".xlsx"
                       :limit="1"
                       :on-remove="handleRemove"
                       :on-change="handleChange"
                       :file-list="fileList"
                       :auto-upload="false">
              <el-button slot="trigger"
                         size="small"
                         type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;"
                         size="small"
                         type="success"
                         :loading="uploadLoading"
                         @click="submitUpload">上传到服务器</el-button>
              <div slot="tip"
                   class="el-upload__tip">只能上传excel文件</div>
            </el-upload>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <handle-res-num :uuid="uuid"
                    width="60%"
                    :handleResDialog="queryResDialog"
                    @handleDialogClose="handleDialogClose"></handle-res-num>
  </div>
</template>

<script>
// 是否冻结 是否兑换
import { getAllNumber, addNumber, delPhone, importNumber, handleRes, updateNumber, exportNumber, getNumCount } from '@/api/mng'
import { parseTime, Base64, downloadFileByPath } from '@/utils/index'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import XLSX from 'xlsx'
import HandleResNum from './handleResNum.vue'
const defaultForm = { res: "" }
export default {
  name: 'TaskMng',
  components: {
    HandleResNum,
  },
  props: {

    activeName: {
      type: String,
      default: '1'
    },
  },
  data() {
    return {
      queryResDialog: false,
      isValid: '',
      resForm: {
        res: '',
        id: ''
      },
      resDialog: false,
      exportLoading: false,
      form: {
        chnl: ''
      },
      editDialog: false,
      uploadLoading: false,
      query: {
        tel: '',
        is_valid: '',
        create_time: [],
        res: ''
      },
      // tell: '',
      path: './号码导入模板.xlsx',
      today: new Date(),
      delLoading: false,
      role: window.sessionStorage.getItem('role'),
      uuid: window.sessionStorage.getItem('uuid'),
      loading: false,
      fileList: [],
      importDialog: false,
      taskData: [],
      page: 0,
      size: 10,
      total: 0,
      resList: [],
      numberImportForm: {
        uuid: window.sessionStorage.getItem('uuid')
      },
      type: '',
      rules: {
        tell: [{ required: true, message: '请填写号码', trigger: 'blur' },
        { min: 11, max: 11, message: '请输入11位号码！', trigger: 'blur' }],
        handler_man: [{ required: true, message: '请填写办理人', trigger: 'blur' }]
      },
      exportTotal: 0
    }
  },
  created() {
    this.initData(0)
  },
  methods: {
    queryHandleDialog() {
      this.queryResDialog = true
    },
    handleDialogClose(val) {
      this.queryResDialog = false
    },
    handleQuery() {

      this.initData(0)

    },
    handleResDialog(id) {
      this.resDialog = true
      this.resForm.id = id
    },
    handlerRes() {
      const params = {
        uuid: this.uuid,
        res: this.resForm.res,
        id: this.resForm.id
      }
      handleRes(params).then(res => {
        console.log(res)
        if (res.publicData.retInfo.retType === 0) {
          this.$notify.success('提交成功')
          this.resDialog = false
          this.initData(0)
        }
      }).catch(e => {
        this.$notify.error('接口超时')
      })
    },
    handleDialog(type, row) {
      this.editDialog = true
      this.type = type
      switch (type) {
        case 'create':
          this.form = JSON.parse(JSON.stringify(defaultForm))

          // this.form.chnl = user.chnl_name
          break;
        case 'update':
          this.form = row
          break;
        default:
          break;
      }
    },
    downloadFileByPath,
    initData(page) {
      this.loading = true
      const params = {
        uuid: this.uuid,
        page: page,
        size: this.size,
        tell: this.query.tell || 'null',
        is_valid: this.query.is_valid || 'null',
        create_time_start: this.query.create_time !== null ? this.query.create_time[0] || 'null' : 'null',
        create_time_end: this.query.create_time !== null ? this.query.create_time[1] || 'null' : 'null',
        res: this.query.res || ''
      }
      getAllNumber(params).then(res => {
        if (res.publicData.retInfo.retType === 0) {
          this.taskData = res.data.results
          this.total = res.data.count
        }
        this.loading = false
      }).catch(e => {
        this.$notify.error('接口超时')
        this.loading = false
      })
    },
    async exportNumber() {
      this.exportLoading = true
      const params1 = {
        uuid: this.uuid,
        is_valid: this.query.is_valid || 'null',
        create_time_start: this.query.create_time !== null ? this.query.create_time[0] || 'null' : 'null',
        create_time_end: this.query.create_time !== null ? this.query.create_time[1] || 'null' : 'null',
        res: this.query.res || ''
      }
      const countRes = await getNumCount(params1)
      const count = await countRes.data.count
      let resData = []
      for (let page = 0; page < count / 1000; page++) {
        const params = {
          uuid: this.uuid,
          page: page,
          size: 1000,
          is_valid: this.query.is_valid || 'null',
          create_time_start: this.query.create_time !== null ? this.query.create_time[0] || 'null' : 'null',
          create_time_end: this.query.create_time !== null ? this.query.create_time[1] || 'null' : 'null',
          res: this.query.res || ''
        }
        await exportNumber(params).then(res => {
          for (let i of res.data.results) {
            // console.log(i)
            i.create_time = this.parseTime(i.create_time)
            resData.push(i)
          }
        })
      }
      console.log(resData)
      const thead = ['客户号码', '渠道', '是否有效', '创建时间', '办理人', '创建人工号', '创建人姓名', '反馈情况', '是否冻结', '是否兑换']
      const filterVal = ['tell', 'chnl', 'is_valid', 'create_time', 'handler_man', 'creator', 'nick_name', 'res', 'is_freeze', 'is_convert']
      const excelData = this.formatJson(filterVal, resData)
      export_json_to_excel(thead, excelData, '号码导出表')
      this.exportLoading = false
      this.$notify.success('导出成功')
    },
    parseTime,
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    submit() {
      const user = JSON.parse(window.sessionStorage.getItem('user'))
      let params = {
        uuid: this.uuid,
        tell: this.form.tell,
        handler_man: this.form.handler_man || '',
        chnl: user.chnl_name,
        res: this.form.res || '',
        is_freeze: this.form.is_freeze || '',
        is_convert: this.form.is_convert || '',
      }
      this.uploadLoading = true
      if (this.type === 'create') {
        this.$refs['form'].validate(valid => {
          if (valid) {
            addNumber(params).then(res => {
              if (res.publicData.retInfo.retType === 0) {
                this.$alert(`${res.data.results}`, '新增成功', {
                  confirmButtonText: '确定'
                });
              } else if (res.publicData.retInfo.retType === 1) {
                this.$alert(`${res.data.results}:${res.data.tell}`, '新增无效', {
                  confirmButtonText: '确定'
                });
              }
              this.initData(0)
              this.editDialog = false
              this.uploadLoading = false
            }).catch(e => {
              this.$notify.error('接口超时')
              this.editDialog = false
              this.uploadLoading = false
            })
          } else {
            this.uploadLoading = false
            return false
          }
        })

      } else if (this.type === 'update') {
        params.id = this.form.id
        console.log(params)
        updateNumber(params).then(res => {
          if (res.publicData.retInfo.retType === 0) {
            this.$notify.success('更改成功')

          }
          this.uploadLoading = false
          this.initData(0)
          this.editDialog = false
        }).catch(e => {
          this.uploadLoading = false
          this.$notify.error('接口超时')
          this.editDialog = false
        })
      }

    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该号码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          uuid: this.uuid,
          id: id
        }
        this.delLoading = true
        delPhone(params).then(res => {
          if (res.publicData.retInfo.retType === 0) {
            this.$notify.success(res.publicData.retInfo.retMsg)
            this.initData(0)
          }
          this.delLoading = false
          this.visible = false
        }).catch(e => {
          this.delLoading = false
          this.visible = false
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSizeChange(val) { },
    handleCurrentChange(page) {
      this.initData(page - 1)
      this.page = page
    },
    handleImport(row) {
      this.importDialog = true
      this.fileList = []
    },
    handleRemove(file, fileList) {
      this.fileList.shift()
    },
    handleChange(file, fileList) {
      this.fileList.push(file)
    },
    formatDate(numb) {
      try {
        if (!isNaN(numb)) {
          let time = new Date((numb - 2) * 24 * 3600000 + 1)
          time.setYear(time.getFullYear() - 70)
          let res = this.parseTime(time)
          return res
        }

      } catch (e) {
        this.$notify.error('时间格式有误')
      }

    },
    submitUpload() {
      if (this.fileList.length > 0) {
        let rd = new FileReader()
        let file = this.fileList[0].raw
        this.uploadLoading = true
        rd.onload = ev => {
          try {
            let wb = XLSX.read(ev.target.result, { type: 'binary' })
            let outData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
            let resStr = ''
            outData.map(i => {
              this.handleExcelData(i, ['客户号码', '办理人', '渠道'])
              resStr += i['客户号码'] + '|' + i['办理人'] + '|' +
                i['渠道'] + '\n'
            })
            console.log(resStr)
            let base64Str = Base64.encode(resStr)
            this.numberImportForm.content = base64Str

            importNumber(this.numberImportForm).then((res) => {
              console.log(res)
              if (res.publicData.retInfo.retType === 0) {
                this.$notify.success('全部导入成功')
              } else if (res.publicData.retInfo.retType === 1) {
                this.$alert(`${res.data.results}:${res.data.tell}`, '新增无效', {
                  confirmButtonText: '确定'
                });
              }
              this.uploadLoading = false
              this.importDialog = false
              this.initData(0)
            }).catch(e => {
              this.$notify.error('接口有误')
              this.uploadLoading = false
            })

          } catch (e) {
            console.log(e)
            this.uploadLoading = false
          }
        }
        rd.readAsBinaryString(file)

      } else {
        this.$message.warning('请选择文件')
        this.uploadLoading = false
      }
    },
    handleExcelData(i, arr) {
      let keyArr = Object.keys(i)
      arr.map(j => {
        i[j] = keyArr.indexOf(j) !== -1 ? i[j] : ''
      })
    },
    // 数组拆分
    getPartList(arr, size) {
      const arrNum = Math.ceil(arr.length / size, 10)
      let index = 0
      let resIndex = 0
      const res = []
      while (index < arrNum) {
        res[index] = arr.slice(resIndex, size + resIndex)
        resIndex += size
        index++
      }
      return res
    }
  },
}
</script>

<style lang="scss" scoped>
</style>